import json
import re

from django.contrib.auth.models import User
from django.http import JsonResponse
# from django.shortcuts import render

# Create your views here.
from group.models import GroupInfo, GroupUsers
from usermanage.models import UserInfo


class GroupManager:
    @staticmethod
    def createGroup(request):
        if request.method == "POST":
            data = json.loads(request.body)
            permission = data.get('permission')
            groupname = data.get('name')
            intro = data.get('intro')
            vis = data.get('visibility')
            if request.user.is_authenticated:
                if GroupInfo.objects.filter(groupName=groupname).exists():
                    return JsonResponse({
                        "status": 5,
                        "message": "园子名已存在"
                    })
                groupinfo_obj = GroupInfo.objects.create(founder=request.user, applyPermission=permission,
                                                         groupName=groupname,
                                                         groupIntro=intro, visibility=vis)
                groupinfo_obj.save()
                guser = GroupUsers.objects.create(group=groupinfo_obj, user=request.user, isgroupadmin=True, status=1)
                guser.save()
                return JsonResponse({
                    "status": 0,
                    "message": "创建成功",
                    "groupid": groupinfo_obj.id
                })
            else:
                return JsonResponse({
                    "status": 6,
                    "message": "用户未登录"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST调用"
            })

    @staticmethod
    def deleteGroup(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('name')
            if GroupInfo.objects.filter(groupName=groupname).exists():
                group_to_be_deleted = GroupInfo.objects.get(groupName=groupname)
            else:
                return JsonResponse({
                    "status": 3,
                    "message": "园子不存在"
                })
            if request.user.is_authenticated:
                if GroupUsers.objects.get(user=request.user).isgroupadmin:
                    group_to_be_deleted.delete()
                    return JsonResponse({
                        "status": 0,
                        "message": "删除园子成功"
                    })
                else:
                    return JsonResponse({
                        "status": 4,
                        "message": "没有删除权限"
                    })
            else:
                return JsonResponse({
                    "status": 6,
                    "message": "请先登录"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST调用"
            })

    @staticmethod
    def searchGroupByName(request):
        if request.method == "POST":
            data = json.loads(request.body)
            key = data.get("key")
            groups = GroupInfo.objects.all().order_by("-createTime")
            group_list = []
            for group in groups:
                if re.search(key, group.groupName):
                    group_dict = {}
                    group_dict['groupid'] = group.id
                    group_dict['groupname'] = group.groupName
                    group_dict['createtime'] = group.createTime
                    group_dict['intro'] = group.groupIntro
                    group_dict['visibility'] = group.visibility
                    group_dict['applyperm'] = group.applyPermission
                    group_list.append(group_dict)
            return JsonResponse({
                "status": 0,
                "group_list": group_list
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST调用"
            })

    @staticmethod
    # 全字匹配
    def getGroupInfo(request):
        if request.method == "POST":
            data = json.loads(request.body)
            type = data.get('type')
            if type == 1:
                groupname = data.get('name')
                if GroupInfo.objects.filter(groupName=groupname).exists():
                    group = GroupInfo.objects.get(groupName=groupname)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            elif type == 2:
                groupid = data.get('id')
                if GroupInfo.objects.filter(id=groupid).exists():
                    group = GroupInfo.objects.get(id=groupid)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })
            return JsonResponse({
                "status": 0,
                "groupid": group.id,
                "groupname": group.groupName,
                "createtime": group.createTime,
                "founder": group.founder.username,
                "intro": group.groupIntro,
                "visibility": group.visibility,
                "applyperm": group.applyPermission,
            })

        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    @staticmethod
    def changeGroupIntro(request):
        if request.method == "POST":
            data = json.loads(request.body)
            intro = data.get('intro')
            type = data.get('type')
            if type == 1:
                groupname = data.get('name')
                if GroupInfo.objects.filter(groupName=groupname).exists():
                    group_obj = GroupInfo.objects.get(groupName=groupname)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            elif type == 2:
                groupid = data.get('id')
                if GroupInfo.objects.filter(id=groupid).exists():
                    group_obj = GroupInfo.objects.get(id=groupid)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })
            group_obj.groupIntro = intro
            group_obj.save()
            return JsonResponse({
                "status": 0,
                "message": "修改简介成功"
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    @staticmethod
    def deleteUser(request):
        if request.method == "POST":
            data = json.loads(request.body)
            type = data.get('type')
            if type == 1:
                groupname = data.get('name')
                if GroupInfo.objects.filter(groupName=groupname).exists():
                    group_obj = GroupInfo.objects.get(groupName=groupname)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            elif type == 2:
                groupid = data.get('id')
                if GroupInfo.objects.filter(id=groupid).exists():
                    group_obj = GroupInfo.objects.get(id=groupid)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })
            username = data.get('username')
            if User.objects.filter(username=username).exists():
                user_obj = User.objects.get(username=username)
            else:
                return JsonResponse({
                    "status": 3,
                    "message": "用户不存在"
                })
            if GroupUsers.objects.filter(user=user_obj, group=group_obj).exists():
                groupuser_obj = GroupUsers.objects.get(user=user_obj, group=group_obj)
                if groupuser_obj.user == request.user:
                    return JsonResponse({
                        "status": 4,
                        "message": "不能删除自己"
                    })
                if groupuser_obj.user == group_obj.founder:
                    return JsonResponse({
                        "status": 4,
                        "message": "不能删除创始人"
                    })
            else:
                return JsonResponse({
                    "status": 3,
                    "message": "用户不在园子中"
                })
            groupuser_obj.delete()
            return JsonResponse({
                "status": 0,
                "message": "删除用户成功"
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    @staticmethod
    def applyJoinGroup(request):
        if request.method == "POST":
            data = json.loads(request.body)
            if request.user.is_authenticated:
                applyuser = request.user
            else:
                return JsonResponse({
                    "status": 6,
                    "message": "请先登录"
                })
            type = data.get('type')
            if type == 1:
                groupname = data.get('name')
                if GroupInfo.objects.filter(groupName=groupname).exists():
                    group_obj = GroupInfo.objects.get(groupName=groupname)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            elif type == 2:
                groupid = data.get('id')
                if GroupInfo.objects.filter(id=groupid).exists():
                    group_obj = GroupInfo.objects.get(id=groupid)
                else:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })
            if group_obj.applyPermission == 3:
                return JsonResponse({
                    "status": 4,
                    "message": "该园子暂时禁止加入"
                })
            if not GroupUsers.objects.filter(user=applyuser, group=group_obj).exists():
                if group_obj.applyPermission == 1:
                    applyuser_obj = GroupUsers.objects.create(user=applyuser, group=group_obj, status=1)
                    applyuser_obj.save()
                    return JsonResponse({
                        "status": 0,
                        "username": request.user.username,
                        "message": "加入园子成功"
                    })
                elif group_obj.applyPermission == 2:
                    applyuser_obj = GroupUsers.objects.create(user=applyuser, group=group_obj)
                    applyuser_obj.save()
                    return JsonResponse({
                        "status": 0,
                        "message": "申请已提交，请等待园子管理员审核"
                    })
            else:
                applyuser_obj = GroupUsers.objects.get(user=applyuser, group=group_obj)
                if applyuser_obj.status == 1:
                    return JsonResponse({
                        "status": 5,
                        "message": "已经位于园子中"
                    })
                elif applyuser_obj.status == 2:
                    if group_obj.applyPermission == 1:
                        applyuser_obj.status = 1
                        applyuser_obj.save()
                        return JsonResponse({
                            "status": 0,
                            "username": request.user.username,
                            "message": "加入园子成功"
                        })
                    elif group_obj.applyPermission == 2:
                        return JsonResponse({
                            "status": 0,
                            "message": "申请已提交，请耐心等待"
                        })
                elif applyuser_obj.status == 3:
                    if group_obj.applyPermission == 1:
                        applyuser_obj.status = 1
                        applyuser_obj.save()
                        return JsonResponse({
                            "status": 0,
                            "username": request.user.username,
                            "message": "加入园子成功"
                        })
                    elif group_obj.applyPermission == 2:
                        applyuser_obj.status = 2
                        applyuser_obj.save()
                        return JsonResponse({
                            "status": 0,
                            "message": "申请已提交，请等待园子管理员审核"
                        })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST调用"
            })

    @staticmethod
    def getApplyList(request):
        if request.method == "POST":
            data = json.loads(request.body)
            if request.user.is_authenticated:
                handleuser = request.user
            else:
                return JsonResponse({
                    "status": 6,
                    "message": "请先登录"
                })
            groupname = data.get('name')
            group_obj = GroupInfo.objects.get(groupName=groupname)
            if group_obj is None:
                return JsonResponse({
                    "status": 3,
                    "message": "园子不存在"
                })
            if GroupUsers.objects.get(user=handleuser).isgroupadmin:
                applyuser = GroupUsers.objects.filter(group=group_obj, status=2)
                applyuser_list = []
                for apply in applyuser:
                    apply_dic = {}
                    applyuser_obj = apply.user
                    applyuserinfo_obj = UserInfo.objects.get(user=applyuser_obj)
                    apply_dic['applyid'] = apply.id
                    apply_dic['username'] = applyuser_obj
                    apply_dic['department'] = applyuserinfo_obj.department
                    apply_dic['realname'] = applyuserinfo_obj.realname
                    apply_dic['nickname'] = applyuserinfo_obj.nickname
                    applyuser_list.append(apply_dic)
                return JsonResponse({
                    "status": 0,
                    "apply_list": applyuser_list
                })
            else:
                return JsonResponse({
                    "status": 4,
                    "message": "没有查看权限"
                })

    @staticmethod
    def handleApplication(request):
        if request.method == "POST":
            data = json.loads(request.body)
            applyid = data.get('applyid')
            operation = data.get('op')
            if request.user.is_authenticated:
                handleuser = request.user
            else:
                return JsonResponse({
                    "status": 6,
                    "message": "请先登录"
                })
            handled_apply_obj = GroupUsers.objects.get(id=applyid, status=2)
            if GroupUsers.objects.get(user=handleuser).isgroupadmin:
                if operation == 1:
                    handled_apply_obj.status = 1
                    handled_apply_obj.save()
                    # 和message对接提供站内信
                    return JsonResponse({
                        "status": 0,
                        "message": "已经允许加入"
                    })
                elif operation == 3:
                    handled_apply_obj.status = 3
                    handled_apply_obj.save()
                    # 和message对接提供站内信
                    return JsonResponse({
                        "status": 0,
                        "message": "已经禁止加入"
                    })
            else:
                return JsonResponse({
                    "status": 4,
                    "message": "没有查看权限"
                })

    @staticmethod
    def addAdmin(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('name')
            newadmin = data.get('newadmin')
            if groupname is not None and newadmin is not None:
                newAdmin = User.objects.get(username=newadmin)
                if newAdmin is None:
                    return JsonResponse({
                        "status": 3,
                        "message": "用户不存在"
                    })
                group = GroupInfo.objects.get(groupName=groupname)
                if group is None:
                    return JsonResponse({
                        "status": 3,
                        "message": "园子不存在"
                    })
                newadmin_obj = GroupUsers.objects.get(user=newAdmin, group=group)
                if newadmin_obj is None:
                    return JsonResponse({
                        "status": 3,
                        "message": "用户不在园子中"
                    })
                newadmin_obj.isgroupadmin = True
                newadmin_obj.save()
                return JsonResponse({
                    "status": 0,
                    "message": "添加园子管理员成功"
                })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })

    @staticmethod
    def getAdminList(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('name')
            group_obj = GroupInfo.objects.get(groupName=groupname)
            if group_obj is None:
                return JsonResponse({
                    "status": 3,
                    "message": "园子不存在"
                })
            admins = GroupUsers.objects.filter(group=group_obj, isgroupadmin=True)
            admin_list = []
            for admin in admins:
                admin_dic = {}
                adminuser = admin.user
                admin_dic['username'] = adminuser
                admin_dic['department'] = adminuser.department
                admin_dic['realname'] = adminuser.realname
                admin_dic['nickname'] = adminuser.nickname
                admin_list.append(admin_dic)
            return JsonResponse({
                "status": 0,
                "admin_list": admin_list
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    @staticmethod
    def getGroupUserList(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('name')
            group_obj = GroupInfo.objects.get(groupName=groupname)
            if group_obj is None:
                return JsonResponse({
                    "status": 3,
                    "message": "园子不存在"
                })
            groupusers = GroupUsers.objects.filter(group=group_obj)
            group_user_list = []
            for admin in groupusers:
                group_user_dic = {}
                groupuser = admin.user
                group_user_dic['username'] = groupuser
                group_user_dic['department'] = groupuser.department
                group_user_dic['realname'] = groupuser.realname
                group_user_dic['nickname'] = groupuser.nickname
                group_user_list.append(group_user_dic)
            return JsonResponse({
                "status": 0,
                "data": {
                    "group_user_list": group_user_list
                }
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    # @staticmethod
    # def getGroupHottest(request):

    @staticmethod
    def changeUserTitleLevel(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('groupname')
            # groupid = data.get('groupid')
            username = data.get('username')
            # userid = data.get('userid')
            level = data.get('level')
            group_obj = GroupInfo.objects.get(groupName=groupname)
            # group_obj = GroupInfo.objects.get(id=groupid)
            user_obj = User.objects.get(username=username)
            # user_obj = User.objects.get(id=userid)
            userinfo_obj = UserInfo.objects.get(user=user_obj)
            groupuser_obj = GroupUsers.objects.get(user=user_obj, group=group_obj)
            groupuser_obj.titleLevel = level
            groupuser_obj.save()
            return JsonResponse({
                "status": 0,
                "message": "修改成功"
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    @staticmethod
    def changeApplyPermission(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('groupname')
            newperm = data.get('permission')
            # groupid = data.get('groupid')
            group_obj = GroupInfo.objects.get(groupName=groupname)
            # group_obj = GroupInfo.objects.get(id=groupid)
            group_obj.applyPermission = newperm
            group_obj.save()
            return JsonResponse({
                "status": 0,
                "message": "修改成功"
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })

    @staticmethod
    def changeVisibility(request):
        if request.method == "POST":
            data = json.loads(request.body)
            groupname = data.get('groupname')
            visibility = data.get('visibility')
            # groupid = data.get('groupid')
            group_obj = GroupInfo.objects.get(groupName=groupname)
            # group_obj = GroupInfo.objects.get(id=groupid)
            group_obj.visibility = visibility
            group_obj.save()
            return JsonResponse({
                "status": 0,
                "message": "修改成功"
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用POST请求"
            })
